/* 
    二次封装axios
*/

import axios from 'axios'
import baseURL from '../../env.js'
import { ElMessage } from 'element-plus'
import router from '../router'
// console.log(baseURL)
const TOKEN_ERROR = 'token错误，请重新登录'
const NETWORK_ERROR = '网络异常，请稍后重试'

// 添加axios实例对象，添加全局配置
let serve = axios.create({
  baseURL,
  timeout: 8000,
})

// 请求拦截器
serve.interceptors.request.use((req) => {
  let headers = req.headers
  //   设置请求头
  if (!headers.Authorization) headers.Authorization = ''
  return req
})

// 响应拦截
serve.interceptors.response.use((res) => {
  let { status, data, msg } = res
  if (status === 200) return data
  else if (status == 4001) {
    ElMessage.error(TOKEN_ERROR)
    router.push('/login')
    return Promise.reject(TOKEN_ERROR)
  } else {
    console.log(res)
    ElMessage.error(msg || NETWORK_ERROR)
    return Promise.reject(msg || NETWORK_ERROR)
  }
})

/** 
    请求核心函数
    *@param {*} options 请求配置
*/

function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
  return serve(options)
}

let a = ['get', 'post', 'put', 'delete', 'patch'].forEach((i) => {
  request[i] = (url, data, options) => {
    return request({ url, data, method: i, ...options })
  }
})

export default request
